package com.gt.web.srv.service.wx;

import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.Refund;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class WechatPayTaskService {

    @Autowired
    private WechatPayService wechatPayService;

//    @Autowired
//    private OrderService orderService;
//
//    @Autowired
//    private RefundService refundService;

    /**
     * 每10分钟检查未支付订单
     */
    @Scheduled(cron = "0 */10 * * * ?")
    public void checkUnpaidOrders() {
//        List<Order> unpaidOrders = orderService.findUnpaidOrders();
//
//        unpaidOrders.forEach(order -> {
//            // 超过30分钟的订单关闭
//            if (order.getCreateTime().plusMinutes(30).isBefore(LocalDateTime.now())) {
//                try {
//                    wechatPayService.closePayment(order.getOrderNo());
//                    orderService.cancelOrder(order.getId());
//                } catch (Exception e) {
//                    // 记录日志
//                }
//            }
//        });
    }

    /**
     * 每30分钟检查处理中的退款
     */
    @Scheduled(cron = "0 */30 * * * ?")
    public void checkProcessingRefunds() {
//        List<RefundRecord> processingRefunds = refundService.findProcessingRefunds();
//
//        processingRefunds.forEach(record -> {
//            try {
//                Refund refund = wechatPayService.queryRefund(record.getRefundNo());
//
//                // 更新退款状态
//                if (!"PROCESSING".equals(refund.getStatus())) {
//                    refundService.handleRefundResult(
//                            record.getRefundNo(),
//                            refund.getStatus(),
//                            refund.getAmount().getRefund()
//                    );
//                }
//
//                // 超过24小时未处理的退款标记为异常
//                else if (record.getCreateTime().plusDays(1).isBefore(LocalDateTime.now())) {
//                    record.setStatus(RefundStatus.ABNORMAL);
//                    refundService.saveRefundRecord(record);
//                }
//            } catch (Exception e) {
//                // 记录日志
//            }
//        });
    }
}